import './App.css';
import { Layout, Menu, Typography, Breadcrumb, Segmented } from 'antd';
import { Routes, Route, useLocation, useNavigate } from 'react-router-dom';
import { Suspense, useEffect, useState } from 'react';
import {
  buildMenuItems,
  routeElements,
  getBreadcrumb,
  getOpenKeysFromPath,
  segmentedOptions,
} from './routes';

function App() {
  const navigate = useNavigate();
  const location = useLocation();
  const selected = location.pathname === '/' ? '/bst' : location.pathname;
  const [openKeys, setOpenKeys] = useState<string[]>(getOpenKeysFromPath(selected));
  useEffect(() => {
    setOpenKeys(getOpenKeysFromPath(selected));
  }, [selected]);
  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Layout.Sider
        width={220}
        theme="light"
        collapsible
        breakpoint="lg"
        collapsedWidth={64}
        style={{ overflow: 'hidden' }}
      >
        <div style={{ padding: 16, fontWeight: 600 }}>数据结构</div>
        <div style={{ height: 'calc(100vh - 64px)', overflowY: 'auto' }}>
          <Menu
            mode="inline"
            selectedKeys={[selected]}
            openKeys={openKeys}
            onOpenChange={(keys) => setOpenKeys(keys as string[])}
            onClick={({ key }) =>
              typeof key === 'string' && key.startsWith('/') && navigate(String(key))
            }
            items={buildMenuItems()}
          />
        </div>
      </Layout.Sider>
      <Layout>
        <Layout.Header style={{ background: '#fff', borderBottom: '1px solid #eee' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Typography.Title level={3} style={{ margin: 0 }}>
              算法可视化
            </Typography.Title>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <Segmented
                options={segmentedOptions}
                value={['/user', '/team', '/files'].includes(selected) ? selected : undefined}
                onChange={(val) => navigate(String(val))}
              />
            </div>
          </div>
        </Layout.Header>
        <Layout.Content style={{ padding: 24 }}>
          <div style={{ marginBottom: 16 }}>
            <Breadcrumb items={getBreadcrumb(selected)} />
          </div>
          <Suspense fallback={<div style={{ padding: 24 }}>加载中...</div>}>
            <Routes>
              {routeElements.map((r) => (
                <Route key={r.path} path={r.path} element={r.element} />
              ))}
            </Routes>
          </Suspense>
        </Layout.Content>
        <Layout.Footer style={{ textAlign: 'center' }}>AlgoStruct Visualizer ©2025</Layout.Footer>
      </Layout>
    </Layout>
  );
}

export default App;
